package com.frank.oj.shiro;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.frank.model.entity.user.Auth;
import com.frank.model.entity.user.Role;
import com.frank.model.entity.user.UserInfo;
import com.frank.oj.mapper.RoleAuthMapper;
import com.frank.oj.service.entity.user.UserInfoEntityService;
import com.frank.oj.service.entity.user.UserRoleEntityService;
import com.frank.oj.utils.JwtUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author frank
 * @Date 2023/12/18
 */
@Component
public class AccountRealm extends AuthorizingRealm {

    @Resource
    private UserRoleEntityService userRoleEntityService;
    @Resource
    private UserInfoEntityService userInfoEntityService;
    @Resource
    private RoleAuthMapper roleAuthMapper;
    @Resource
    private JwtUtils jwtUtils;

    /**
     * 权限认证
     *
     * @param principalCollection 身份集合
     * @return 权限信息
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 获取当前用户
        AccountProfile user = (AccountProfile) principalCollection.getPrimaryPrincipal();

        // 初始化权限和角色列表
        List<String> permissions = new ArrayList<>();
        List<String> roleNameList = new ArrayList<>();

        // 获取当前用户的角色列表
        List<Role> roles = userRoleEntityService.getRolesByUid(user.getUid());
        for (Role role : roles) {
            // 添加角色到角色列表
            roleNameList.add(role.getRole());

            // 遍历角色的权限列表，将权限添加到权限列表
            for (Auth auth : roleAuthMapper.getRoleAuths(role.getId()).getAuths()) {
                permissions.add(auth.getPermission());
            }
        }

        // 创建简单的授权信息对象
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        // 添加角色列表到授权信息对象
        authorizationInfo.addRoles(roleNameList);
        // 添加权限列表到授权信息对象
        authorizationInfo.addStringPermissions(permissions);

        // 返回授权信息对象
        return authorizationInfo;
    }


    /**
     * 身份认证
     *
     * @param authenticationToken 身份令牌
     * @return 身份认证信息
     */
      @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 将authenticationToken转换为JwtToken
        JwtToken jwt = (JwtToken) authenticationToken;
        // 通过jwtUtils工具获取jwt中的subject，即userId
        String userId = jwtUtils.getClaimByToken((String) jwt.getPrincipal()).getSubject();

        // 创建LambdaQueryWrapper用于查询UserInfo
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        // 根据userId查询UserInfo，并选择需要的属性
        queryWrapper.eq(UserInfo::getUuid, userId)
                .select(UserInfo::getUuid, UserInfo::getUsername, UserInfo::getNickname, UserInfo::getRealname,
                        UserInfo::getTitleName, UserInfo::getTitleColor, UserInfo::getAvatar, UserInfo::getStatus);

        // 查询UserInfo
        UserInfo userInfo = userInfoEntityService.getOne(queryWrapper, false);
        // 如果查询结果为null，则抛出UnknownAccountException异常
        if (userInfo == null) {
            throw new UnknownAccountException("账户不存在！");
        }
        // 如果查询结果的状态为封禁，则抛出LockedAccountException异常
        if (userInfo.getStatus() == 1) {
            throw new LockedAccountException("该账户已被封禁，请联系管理员进行处理！");
        }
        // 创建AccountProfile对象，并将UserInfo的属性复制到该对象中
        AccountProfile profile = new AccountProfile();
        BeanUtil.copyProperties(userInfo, profile);
        // 设置profile的uid属性为userInfo的uuid
        profile.setUid(userInfo.getUuid());
        // 返回通过SimpleAuthenticationInfo包装的profile对象
        return new SimpleAuthenticationInfo(profile, jwt.getCredentials(), getName());
    }


    /**
     * 用于判断给定的AuthenticationToken是否为JwtUtils的实例
     *
     * @param token 要判断的AuthenticationToken
     * @return 如果token是JwtUtils的实例，则返回true；否则返回false
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

}
